import '@css/index.scss'
import {userListApi,deleteUserApi} from '@utils/api/user'
window.addEventListener('DOMContentLoaded',async()=>{
   userListApi().then(({rows})=>{
     render(rows)
   }).catch(err=>{
     if(err=="401err"){
        alert('您的token已经失效,请重新登录')
        window.location.href="login.html"
     }
   })
  
   /* 单击删除按钮执行删除操作 */
   document.querySelector('tbody').addEventListener('click',async(e)=>{
      if(e.target.className=='delBtn'){
         //获取删除的编号
         let _id=e.target.getAttribute('data-id')
         const result=await deleteUserApi(_id)
         console.log('删除后的结果',result);
      }
   })
})
const render=rows=>{
    document.querySelector("tbody").innerHTML=rows.map(item=>`<tr>
        <td>${item.username}</td>
        <td>${item.age}</td>
        <td>${item.birthday}</td>
        <td>${item.phone}</td>
        <td>${item.gender==1?'男':'女'}</td>
        <td><img src="http://127.0.0.1:3002/images/${item.avatar}" class='headImg'></td>
        <td>
            <button class="detailBtn">查看</button>
            <button class="delBtn" data-id="${item._id}">删除</button>
        </td>
    </tr>`).join("")
}
